package com.ufida.ids.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.hereway.core.servlet.BaseServlet;
import com.hereway.core.util.ParamUtils;
import com.ufida.ids.model.AppModel;
import com.ufida.ids.model.UserMappingModel;
import com.ufida.ids.service.IAppService;
import com.ufida.ids.service.IUserMappingService;
import com.ufida.ids.util.CipherUtil;
import com.ufida.ids.util.Constants;
import com.ufida.ids.util.ExtUtil;

public class UserMappingServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(UserMappingServlet.class);

	@Autowired
	private IUserMappingService userMappingService;
	@Autowired
	private IAppService appService;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserMappingServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		//获取操作类型
		String action = ParamUtils.getParameter(request, "action");
		logger.debug("action:"+action);
		if ("getUserMappingByStaffId".equals(action)){
			getUserMappingByStaffId(request, response);
		}else if("add".equals(action)){
			add(request, response);
		}else if("active".equals(action)){
			active(request, response);
		}else if("unactive".equals(action)){
			unactive(request, response);
		}
	}
	
	private void getUserMappingByStaffId(HttpServletRequest request, HttpServletResponse response) {
		String staffId = request.getParameter("staffId");
		List retL = new ArrayList();
		try {
			List<AppModel> appL = appService.getAllActiveApp();
			for(AppModel app: appL){
				UserMappingModel userMappingModel = userMappingService.findByUserApp(Long.parseLong(staffId), app.getAppId());
				if(null != userMappingModel){
					userMappingModel.setAppName(app.getAppName());
					retL.add(userMappingModel);
				}else{
					UserMappingModel tempUserMappingModel = new UserMappingModel();
					tempUserMappingModel.setAppId(app.getAppId());
					tempUserMappingModel.setAppName(app.getAppName());
					tempUserMappingModel.setStaffId(Long.parseLong(staffId));
					tempUserMappingModel.setUserName("");
					tempUserMappingModel.setPassword("");
					tempUserMappingModel.setEntityStatus(Constants.STATUS_UNKNOW);
					retL.add(tempUserMappingModel);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		String retStr = ExtUtil.getJosonStr(retL,retL.size());
		System.out.println("retStr:"+retStr);
		writeResponse(response, retStr);
	}
	
	private void add(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[add staff...]");
		boolean flag = true;
		
		JSONObject jo = JSONObject.fromObject(request.getParameter("para"));
		
		JSONArray ja = jo.optJSONArray("userMappingArr");
		String staffId = "";
		String appId = "";
		String userName = "";
		String password = "";
		String entityStatus = "";
		
		String retStr = "";
		
		try{
			//先删除所有数据
			List oldL = userMappingService.loadAll();
			userMappingService.delete(oldL);
			//再添加数据
			for(int i = 0;i <ja.size(); i++){
				JSONObject userMappingItem = ja.getJSONObject(i);
				staffId = userMappingItem.optString("staffId");
				appId = userMappingItem.optString("appId");
				userName = userMappingItem.optString("userName");
				password = userMappingItem.optString("password");
				entityStatus = userMappingItem.optString("entityStatus");
				
				if("".equals(userName)){//如果用户名为空，不保存该条记录
					continue;
				}
				
				UserMappingModel userMappingModel = new UserMappingModel();
				userMappingModel.setAppId(Long.parseLong(appId));
				//对密码进行加密
				if(!"".equals(password)){
					userMappingModel.setPassword(CipherUtil.generatePassword(password));
				}else{
					userMappingModel.setPassword(password);
				}
				userMappingModel.setUserName(userName);
				userMappingModel.setStaffId(Long.parseLong(staffId));
				userMappingModel.setCreateTs(new Date());
				userMappingModel.setEntityStatus(Short.parseShort(entityStatus));
				userMappingService.save(userMappingModel);
			}
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		retStr = ExtUtil.getJosonStr(flag);
		writeResponse(response, retStr);
	}
	
	private void active(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[active userMapping...]");
		JSONObject jo = JSONObject.fromObject(request.getParameter("para"));
		//JSONArray idArr = (JSONArray)jo.opt("idArr");
		String retStr = "";
		String staffId = jo.optString("staffId");
		String appId = jo.optString("appId");
		try {
			UserMappingModel userMappingModel = userMappingService.findByUserApp(Long.parseLong(staffId), Long.parseLong(appId));
			userMappingModel.setEntityStatus(Constants.STATUS_ACTIVE);
			userMappingService.update(userMappingModel);
			retStr = ExtUtil.getJosonStr(true);
		} catch (Exception e) {
			retStr = ExtUtil.getJosonStr(false);
			e.printStackTrace();
		}
		writeResponse(response, retStr);
	}
	
	private void unactive(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[active userMapping...]");
		JSONObject jo = JSONObject.fromObject(request.getParameter("para"));
		//JSONArray idArr = (JSONArray)jo.opt("idArr");
		String retStr = "";
		String staffId = jo.optString("staffId");
		String appId = jo.optString("appId");
		try {
			UserMappingModel userMappingModel = userMappingService.findByUserApp(Long.parseLong(staffId), Long.parseLong(appId));
			userMappingModel.setEntityStatus(Constants.STATUS_UNACTIVE);
			userMappingService.update(userMappingModel);
			retStr = ExtUtil.getJosonStr(true);
		} catch (Exception e) {
			retStr = ExtUtil.getJosonStr(false);
			e.printStackTrace();
		}
		writeResponse(response, retStr);
	}
	
//	
//	private void unactive(HttpServletRequest request, HttpServletResponse response) {
//		logger.debug("[unactive staff...]");
//		JSONObject jo = JSONObject.fromObject(request.getParameter("para"));
//		JSONArray idArr = (JSONArray)jo.opt("idArr");
//		String idStr =StringUtil.buildIdsStr(idArr);
//		String retStr = "";
//		try {
//			List<StaffModel> l = staffService.find(idStr);
//			for(StaffModel staffModel:l){
//				staffModel.setEntityStatus(Constants.STATUS_UNACTIVE);
//				staffService.update(staffModel);
//			}
//			retStr = ExtUtil.getJosonStr(true);
//		} catch (Exception e) {
//			retStr = ExtUtil.getJosonStr(false);
//		}
//		writeResponse(response, retStr);
//	}
//	
//	private void resetPWD(HttpServletRequest request, HttpServletResponse response) {
//		logger.debug("[resetPWD staff...]");
//		JSONObject jo = JSONObject.fromObject(request.getParameter("para"));
//		JSONArray idArr = (JSONArray)jo.opt("idArr");
//		String idStr =StringUtil.buildIdsStr(idArr);
//		String retStr = "";
//		try {
//			List<StaffModel> l = staffService.find(idStr);
//			for(StaffModel staffModel:l){
//				staffModel.setPassword(Constants.INIT_PWD);
//				staffService.update(staffModel);
//			}
//			retStr = ExtUtil.getJosonStr(true);
//		} catch (Exception e) {
//			retStr = ExtUtil.getJosonStr(false);
//		}
//		writeResponse(response, retStr);
//	}
}
